﻿using System;
using System.IO;
using System.Xml.Serialization;

public static class XmlTool
{
	public static T Load<T>(string path) where T : new() {
		T t = default(T);

		if (!File.Exists(path))
		{
			MyLog.LogError("Error : File doesn't Exist : " + path);
			return t;
		}

		FileStream fs = null;
		try {
			XmlSerializer xs = new XmlSerializer(typeof(T));
			fs = new FileStream(path, FileMode.Open, FileAccess.Read);
			t = (T)xs.Deserialize(fs);
			fs.Close();
			return t;
		} catch (Exception e){
			if (fs != null)
				fs.Close();
			throw new Exception("Xml deserialization failed!" + e);
		}


		return t;
	}

	public static void Save<T>(string path, T t) {
		if (t == null) {
			MyLog.LogError("Serilize Object is null" + typeof(T));
			return;
		}

		FileStream fs = null;
		try {
			XmlSerializer xs = new XmlSerializer(typeof(T));
			fs = new FileStream(path, FileMode.Create, FileAccess.Write);
			xs.Serialize(fs, t);
			fs.Close();
		} catch (Exception e) {
			if (fs != null)
				fs.Close();
			throw new Exception("Xml serialization failed : " + e);
		}
	}
}
